﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;
using System.IO;
using MyGridView.BLL;


public partial class Default2 : System.Web.UI.Page
{
    SqlHelper sqlHelper = new SqlHelper();
    private static DataTable dtCol;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
            bindData(true);
        this.BtSave.Enabled = false;
    }

    /// <summary>
    /// 数据绑定
    /// </summary>
    /// <param name="refresh"></param>
    private void bindData(bool refresh)
    {

        if (refresh || dtCol == null)
        {
            DataSet ds = sqlHelper.getDs("Select ID,projectName,tableName,columnName,columnType,columnMemo from TColumn where 1=1 order by ID desc", CommandType.Text, null, "TColumn");
            dtCol = ds.Tables[0];
        }

        this.myGridView.DataSource = dtCol.DefaultView;
        this.myGridView.DataBind();
    }

    /// <summary>
    /// 删除
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    public void txtDel_Click(object sender, EventArgs e)
    {
        int id = Convert.ToInt32(((LinkButton)sender).CommandArgument);

        //从数据库中删除
        string Sql;
        Sql = "Delete from TColumn where ID=" + id;
        sqlHelper.ExecuteSql(Sql, CommandType.Text, null);

        //从内存中删除
        DataRow[] dr = dtCol.Select("ID=" + id);
        if (dr.Length > 0)
            dtCol.Rows.Remove(dr[0]);
        this.bindData(false);
    }

    /// <summary>
    /// 新增
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void BtAdd_Click(object sender, EventArgs e)
    {
        DataRow row = dtCol.NewRow();
        row["ID"] = (int)getMaxIdInTable(dtCol, "ID") + 1;
        //row["BirthDay"] = DateTime.Now;
        dtCol.Rows.Add(row);

        this.myGridView.EditIndex = dtCol.Rows.Count - 1;
        this.bindData(false);
        this.BtSave.Enabled = true;
    }

    /// <summary>
    /// 保存
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void BtSave_Click(object sender, EventArgs e)
    {
        if (CreatPro.Text == "" && CreatTB.Text == "")
        {
            CreatPro.Text = "Project1";
            CreatTB.Text = "Table1";
        }
        int i = this.myGridView.EditIndex;
        string projectName = CreatPro.Text;
        string tableName = CreatTB.Text;
        string columnName = ((TextBox)this.myGridView.Rows[i].FindControl("txtColumnName")).Text.ToString();
        string columnType = ((RadioButtonList)this.myGridView.Rows[i].FindControl("txtColumnType")).Text.ToString();
        string columnMemo = ((TextBox)this.myGridView.Rows[i].FindControl("txtColumnMemo")).Text.ToString();
        //string projectName = ((TextBox)this.myGridView.Rows[i].FindControl("txtProjectName")).Text.ToString();
        //DateTime tableName = ((Calendar)this.myGridView.Rows[i].FindControl("txtTableName")).SelectedDate;

        string Sql;
        Sql = "Insert Into TColumn(ProjectName,TableName,ColumnName,ColumnType,ColumnMemo) values('" + projectName + "','" + tableName + "','" + columnName + "','" + columnType + "','" + columnMemo + "')";
        sqlHelper.ExecuteSql(Sql, CommandType.Text, null);
        //this.myGridView.EditIndex = -1;
        //this.bindData(true);
        //this.BtSave.Enabled = false;

        //string Sql1;
        //Sql1 = "Insert Into TProject(ProjectName) values('" + projectName + "')";
        //sqlHelper.ExecuteSql(Sql1, CommandType.Text, null);

        //string Sql1;
        //Sql1 = "Insert Into TTable(TableName) values('" + tableName + "')";
        //sqlHelper.ExecuteSql(Sql1, CommandType.Text, null);

        this.myGridView.EditIndex = -1;
        this.bindData(true);
        this.BtSave.Enabled = false;
    }

    /// <summary>
    /// 得到指定表中关键字的最大值
    /// </summary>
    /// <param name="table"></param>
    /// <param name="keyID"></param>
    /// <returns></returns>
    private object getMaxIdInTable(DataTable table, string keyID)
    {
        if (table.Rows.Count == 0)
            return 0;
        DataView dv = new DataView();
        dv.Table = table;
        dv.Sort = keyID + " Desc";
        return dv[0][keyID];
    }

    /// <summary>
    /// 用户取消事件
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void myGridView_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        this.myGridView.EditIndex = -1;
        this.bindData(true);
    }

    /// <summary>
    /// 用户更新事件
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void myGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        int i = this.myGridView.EditIndex;
        if (dtCol.Rows[i].RowState == DataRowState.Added)
        {
            BtSave_Click(sender, e);
            dtCol.Rows[i].AcceptChanges();
        }
        else
        { //表示修改
            int id = Convert.ToInt16(this.myGridView.Rows[i].Cells[1].Text);
            //string projectName = ((TextBox)this.myGridView.Rows[i].FindControl("txtProjectName")).Text.ToString();
            //string tableName = ((TextBox)this.myGridView.Rows[i].FindControl("txtTableName")).Text.ToString();
            string columnName = ((TextBox)this.myGridView.Rows[i].FindControl("txtColumnName")).Text.ToString();
            string columnType = ((RadioButtonList)this.myGridView.Rows[i].FindControl("txtColumnType")).Text.ToString();
            string columnMemo = ((TextBox)this.myGridView.Rows[i].FindControl("txtColumnMemo")).Text.ToString();
            string Sql;
            Sql = "Update TColumn Set ColumnName='" + columnName + "',ColumnType='" + columnType + "',ColumnMemo='" + columnMemo + "' where id=" + id;
            sqlHelper.ExecuteSql(Sql, CommandType.Text, null);
            this.myGridView.EditIndex = -1;
            this.bindData(true);
            this.BtSave.Enabled = false;
        }
    }

    /// <summary>
    /// 用户删除事件
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void myGridView_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        int selectIndex = e.RowIndex;

        //这里的 Cells[1]　对应的是编号列
        int id = Convert.ToInt16(this.myGridView.Rows[selectIndex].Cells[1].Text);

        string Sql;
        Sql = "Delete from TColumn where ID=" + id;
        sqlHelper.ExecuteSql(Sql, CommandType.Text, null);

        //从内存中删除
        DataRow[] dr = dtCol.Select("ID=" + id);
        dtCol.Rows.Remove(dr[0]);
        this.bindData(false);
    }

    /// <summary>
    /// 用户编辑事件
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void myGridView_RowEditing(object sender, GridViewEditEventArgs e)
    {
        this.myGridView.EditIndex = e.NewEditIndex;
        this.bindData(false);
    }

    protected void myGridView_DataBound(object sender, EventArgs e)
    {
        string columnName = "";
        foreach (GridViewRow r in this.myGridView.Rows)
        {
            //columnName = ((Label)r.FindControl("showColumnName")).Text;
            ((LinkButton)r.FindControl("txtDel")).Attributes.Add("onclick", "return checkDel(" + columnName + ")");
        }
    }

    string strColumn = "";
    string strGetSet = "";
    string strQueryColumnName = "";

    private void CreateCS(string projectName, string tableName)
    {
        bool textEmpty = false;
        DataSet ds = sqlHelper.getDs("Select ID,projectName,tableName,columnName,columnType,columnMemo from TColumn where 1=1 and projectName='" + projectName + "' and tableName='" + tableName + "'", CommandType.Text, null, "TColumn");
        dtCol = ds.Tables[0];

        string columnMemo=string.Empty;
        string strProjectName = dtCol.Rows[0]["projectName"].ToString();
        string strTableName = dtCol.Rows[0]["tableName"].ToString();

        for (int j = 0; j < dtCol.Rows.Count; j++)
        {
            if (dtCol.Rows[j]["columnName"].ToString() != "" && dtCol.Rows[j]["columnType"].ToString() != "")
            {
                if (dtCol.Rows[j]["columnMemo"].ToString() != "")
                {
                    columnMemo = "//" + dtCol.Rows[j]["columnMemo"].ToString();
                }
                strColumn += "\r\n\t\tprivate " + dtCol.Rows[j]["columnType"].ToString() + " _" + dtCol.Rows[j]["columnName"].ToString() + ";" + columnMemo;
                strGetSet += "\r\n\t\tpublic " + dtCol.Rows[j]["columnType"].ToString() + " " + dtCol.Rows[j]["columnName"].ToString() + "\r\n\t\t{\r\n\t\t\tget { return _" + dtCol.Rows[j]["columnName"].ToString() + "; }\r\n\t\t\tset { _" + dtCol.Rows[j]["columnName"].ToString() + " = value; }\r\n\t\t}";
                strQueryColumnName += "\r\n\t\t\tpropName = \"" + dtCol.Rows[j]["columnName"].ToString() + "\";" + columnMemo + "\r\n\t\t\tif (ps[propName] != null && ps[propName].Length > 0)\r\n\t\t\t{\r\n\t\t\t\tparts.Add(BaseHelper.MakeCriteria(propName, \" = \"));\r\n\t\t\t\tparameters.Add(propName, ps[propName]);\r\n\t\t\t}";
                columnMemo = string.Empty;
            }
            else
            {
                textEmpty = true;
            }
        }
        //Response.Write("(i - 5) / 2=" + (i - 5) / 2 + " i="+i);
        //Response.Write(strProjectName);
        //Response.Write(strTableName);
        //Response.Write(strColumn);
        if (!textEmpty)
        {
            WriteDataFile(strProjectName, strTableName, strColumn, strGetSet);
            WriteQueryFile(strProjectName, strTableName, strQueryColumnName);
            WriteFacadeFile(strProjectName, strTableName);
            WriteFacadeCSFile(strProjectName, strTableName);
        }
        else
        {
            Response.Write("<script language=\"javascript\">alert(\"错误！不允许文本框为空！\")</script>");
        }
        //foreach (string key in keys)
        //{
        //    Response.Write("<br>" + key + ":");
        //    //if (key.StartsWith("ColumnName"))
        //    //{
        //    strColumn += "private " + Request.Form["ColumnType2"] + " " + Request.Form["ColumnName2"] + ";";

        //    //}
        //    Response.Write(strColumn);
        //}
    }

    //WriteDataFile 
    public static bool WriteDataFile(string strProjectName, string strTableName, string strColumn, string strGetSet)
    {
        string path = HttpContext.Current.Server.MapPath("~\\cs\\");
        Encoding code = Encoding.GetEncoding("gb2312");
        //如果目录不存在,将创建目录
        if (!Directory.Exists(path))
        {
            Directory.CreateDirectory(path);
        }
            // 读取模板文件 
        string temp = HttpContext.Current.Server.MapPath("~\\model.htm");
        StreamReader sr = null;
        StreamWriter sw = null;
        string str = "";
        try
        {
            sr = new StreamReader(temp, code);
            str = sr.ReadToEnd(); // 读取文件 
        }
        catch (Exception exp)
        {
            HttpContext.Current.Response.Write(exp.Message);
            HttpContext.Current.Response.End();
            sr.Close();
        }


        string csFileName = "T" + strTableName + ".cs";
        // 替换内容 
        // 这时,模板文件已经读入到名称为str的变量中了 
        str = str.Replace("ProjectName", strProjectName); //模板页中的ShowArticle 
        str = str.Replace("TableName", strTableName);
        str = str.Replace("ColumnName", strColumn);
        str = str.Replace("GetSet", strGetSet);
        // 写文件 
        try
        {
            sw = new StreamWriter(path + csFileName, false, code);
            sw.Write(str);
            sw.Flush();
        }
        catch (Exception ex)
        {
            HttpContext.Current.Response.Write(ex.Message);
            HttpContext.Current.Response.End();
        }
        finally
        {
            sw.Close();
        }
        return true;

        //此函数放在Conn.CS基类中了 
        //在添加新闻的代码中引用 注：工程名为Hover 

        //if(Hover.Conn.WriteDataFilethis.Title.Text.ToString),this.Content.Text.ToString),this.Author.Text.ToString))) 
        //{ 
        //    Response.Write("添加成功"); 
        //} 
        //else 
        //{ 
        //    Response.Write("生成HTML出错!"); 
        //} 

    }
    //WriteQueryFile
    public static bool WriteQueryFile(string strProjectName, string strTableName, string strQueryColumnName)
    {
        string path = HttpContext.Current.Server.MapPath("~\\cs\\");
        Encoding code = Encoding.GetEncoding("gb2312");
        //如果目录不存在,将创建目录
        if (!Directory.Exists(path))
        {
            Directory.CreateDirectory(path);
        }
        // 读取模板文件 
        string temp = HttpContext.Current.Server.MapPath("~\\model2.htm");
        StreamReader sr = null;
        StreamWriter sw = null;
        string str = "";
        try
        {
            sr = new StreamReader(temp, code);
            str = sr.ReadToEnd(); // 读取文件 
        }
        catch (Exception exp)
        {
            HttpContext.Current.Response.Write(exp.Message);
            HttpContext.Current.Response.End();
            sr.Close();
        }


        string csFileName = strTableName + "Query.cs";
        // 替换内容 
        // 这时,模板文件已经读入到名称为str的变量中了 
        str = str.Replace("ProjectName", strProjectName); //模板页中的ShowArticle 
        str = str.Replace("TableName", strTableName);
        str = str.Replace("QueryColumnName", strQueryColumnName);
        // 写文件 
        try
        {
            sw = new StreamWriter(path + csFileName, false, code);
            sw.Write(str);
            sw.Flush();
        }
        catch (Exception ex)
        {
            HttpContext.Current.Response.Write(ex.Message);
            HttpContext.Current.Response.End();
        }
        finally
        {
            sw.Close();
        }
        return true;
    }
    //WriteFacadeCSFile
    public static bool WriteFacadeCSFile(string strProjectName, string strTableName)
    {
        string path = HttpContext.Current.Server.MapPath("~\\cs\\");
        Encoding code = Encoding.GetEncoding("gb2312");
        //如果目录不存在,将创建目录
        if (!Directory.Exists(path))
        {
            Directory.CreateDirectory(path);
        }
        // 读取模板文件 
        string temp = HttpContext.Current.Server.MapPath("~\\model3.htm");
        StreamReader sr = null;
        StreamWriter sw = null;
        string str = "";
        try
        {
            sr = new StreamReader(temp, code);
            str = sr.ReadToEnd(); // 读取文件 
        }
        catch (Exception exp)
        {
            HttpContext.Current.Response.Write(exp.Message);
            HttpContext.Current.Response.End();
            sr.Close();
        }


        string csFileName = strTableName + ".aspx.cs";
        // 替换内容 
        // 这时,模板文件已经读入到名称为str的变量中了 
        str = str.Replace("ProjectName", strProjectName); //模板页中的ShowArticle 
        str = str.Replace("TableName", strTableName);
        // 写文件 
        try
        {
            sw = new StreamWriter(path + csFileName, false, code);
            sw.Write(str);
            sw.Flush();
        }
        catch (Exception ex)
        {
            HttpContext.Current.Response.Write(ex.Message);
            HttpContext.Current.Response.End();
        }
        finally
        {
            sw.Close();
        }
        return true;
    }
    //WriteFacadeFile
    public static bool WriteFacadeFile(string strProjectName, string strTableName)
    {
        string path = HttpContext.Current.Server.MapPath("~\\cs\\");
        Encoding code = Encoding.GetEncoding("gb2312");
        //如果目录不存在,将创建目录
        if (!Directory.Exists(path))
        {
            Directory.CreateDirectory(path);
        }
        // 读取模板文件 
        string temp = HttpContext.Current.Server.MapPath("~\\model4.htm");
        StreamReader sr = null;
        StreamWriter sw = null;
        string str = "";
        try
        {
            sr = new StreamReader(temp, code);
            str = sr.ReadToEnd(); // 读取文件 
        }
        catch (Exception exp)
        {
            HttpContext.Current.Response.Write(exp.Message);
            HttpContext.Current.Response.End();
            sr.Close();
        }


        string csFileName = strTableName + ".aspx";
        // 替换内容 
        // 这时,模板文件已经读入到名称为str的变量中了 
        str = str.Replace("ProjectName", strProjectName); //模板页中的ShowArticle 
        str = str.Replace("TableName", strTableName);
        // 写文件 
        try
        {
            sw = new StreamWriter(path + csFileName, false, code);
            sw.Write(str);
            sw.Flush();
        }
        catch (Exception ex)
        {
            HttpContext.Current.Response.Write(ex.Message);
            HttpContext.Current.Response.End();
        }
        finally
        {
            sw.Close();
        }
        return true;
    }

    protected void BtCreate_Click(object sender, EventArgs e)
    {
        string projectName = CreatPro.Text;
        string tableName = CreatTB.Text;
        if (projectName != "" && tableName != "")
        {
            CreateCS(projectName, tableName);
        }
    }
    protected void myGridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        myGridView.PageIndex = e.NewPageIndex;
        myGridView.DataBind();
    }
}